package cn.yj.core.business.controller;

import cn.yj.annotation.pagehelper.page.OrderBy;
import cn.yj.cgs.dba.entity.UserAddress;
import cn.yj.syslog.common.LogType;
import cn.yj.syslog.common.OperateLog;
import cn.yj.commons.utils.FileUtils;
import cn.yj.commons.utils.MapUtils;
import cn.yj.commons.utils.StringUtils;
import cn.yj.config.annotation.Anonymous;
import cn.yj.config.web.AppBaseController;
import cn.yj.core.business.service.iservice.IUserAddressService;
import cn.yj.entity.R;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;

/**
 * 用户地址
 *
 * @author 永健
 * @since 2021-05-10 09:56
 */
@RequestMapping("/address")
@RestController
public class UserAddressController extends AppBaseController<UserAddress> {

    @Resource
    private IUserAddressService userAddressService;

    @GetMapping("/pageList")
    public R pageList(@RequestParam Map<String, Object> params) {
        params.put("userCode",getUserCode());
        return success(userAddressService.pageList(params, page(new OrderBy(OrderBy.Direction.DESC, "create_time",
                "is_default"))));
    }

    @PostMapping("/add")
    @OperateLog(describe = "添加地址")
    public R add(@RequestBody UserAddress userAddress) {
        userAddress.setUserCode(getUserCode());
        return result(userAddressService.addAddress(userAddress));
    }

    @OperateLog(describe = "更新地址")
    @PostMapping("/update")
    public R update(@RequestBody UserAddress userAddress) {
        return result(userAddressService.updateAddress(userAddress));
    }

    @OperateLog(describe = "更改默认地址",type = LogType.UPDATE)
    @PostMapping("/updateDefault")
    public R updateDefault(@RequestBody Map<String, Object> params) {
        String[] keys = {"id", "isDefault"};
        MapUtils.validateKeyValueIsEmpty(params, keys);
        return result(userAddressService.updateDefault(Integer.parseInt(params.get("id").toString()),
                Boolean.parseBoolean(params.get("isDefault").toString())));
    }

    @Anonymous
    @GetMapping("/getAreaList")
    public R getAreaList() throws UnsupportedEncodingException {
        String fileContent = FileUtils.getFileContent("classpath:region.json", this.getClass());
        return success(StringUtils.isNotBlank(fileContent)? JSON.parseArray(fileContent):new ArrayList<>());
    }

    @GetMapping("/getDefaultAddr")
    public R getDefaultAddr()  {

        return success(userAddressService.getDefaultAddr(getUserCode()));
    }

    @OperateLog(describe = "删除地址",type = LogType.DELETE)
    @DeleteMapping("/remove/{id}")
    public R removeById(@PathVariable Integer id){
        return success(userAddressService.removeById(id));
    }


}
